<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <link rel="stylesheet" href="css/reset.css">
    <style>
        .box {
            width: 300px;
            height: 200px;
            padding: 20px 50px;
            border-radius: 5px;
            background-color: gainsboro;
        }

        .box p {
            width: 200px;
            height: 40px;
            margin-bottom: 20px;
            border-radius: 5px;
            border: 1px solid gainsboro;
        }

        .box p input {
            width: 100%;
            height: 100%;
            border-radius: 5px;
            padding: 0 10px;
        }
    </style>
</head>

<body>
    <div class="box">
        <p>
            <input type="text" placeholder="手机号/用户名/邮箱">
        </p>
        <p>
            <input type="password" placeholder="密码">
        </p>
        <p>
            <input type="button" value="登录">
        </p>
    </div>
</body>

</html>
<script>
    function objToSearchString(obj) {
        let str=''
        for (const key in obj) {
            str += `${key}=${obj[key]}&`
        }
        return str.slice(0,str.length-1)
    }
    // 封装ajax
    function ajax(method, url, params, cb) {
        let xhr = new XMLHttpRequest()

        xhr.open(method, method == 'get' ? url + '?' + objToSearchString(params) : url)

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                cb(JSON.parse(xhr.responseText))
            }
        }
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        xhr.send(method == 'get' ? null : objToSearchString(params))
    }
    // 给登录按钮绑定点击事件
    let inputs = document.querySelectorAll('.box input')
    inputs[2].onclick = () => {
        if (inputs[0].value && inputs[1].value) {
            
            if (/^1[3-9]\d{9}$/.test(inputs[0].value) || /^[a-z]{1,}$/.test(inputs[0].value) || /^\w+@[0-9a-z]{1,}\.(com|cn|org)$/.test(inputs[0].value) && /^[1-9]{4}$/.test(inputs[1].value)) {
                ajax('get','https://yantianfeng.com/api/login',{username:inputs[0].value,password:inputs[1].value},function (data) {
                    if (data.status == 200) {
                        alert('登陆成功')
                    } else {
                        alert('登陆失败')
                    }
                })
            } else {
                alert('请输入正确的手机号或密码')
            }
        } else {
            alert('用户名或密码不能为空')       
        }
    }
</script>